import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 100,
    isNavShow: true, //底部导航显隐
    cartData: [] //购物车数据
  },

  // 计算属性
  getters: {
    showNav(state) {
      return state.isNavShow
    },
    getCartData(state) {
      return state.cartData
    },
    totalCount(state) {  //总数量
      return state.cartData.reduce((total, cur) => total + cur.count, 0);
    },
    totalAmount(state) {  //总金额
      return state.cartData.reduce((total, cur) => total + cur.count * cur.product_uprice, 0);
    }
  },
  // mutations处理同步
  mutations: {
    add(state) {
      state.count++
    },
    del(state) {
      state.count--
    },
    NAVSHOW(state) {
      state.isNavShow = true
    },
    HIDENAV(state) {
      state.isNavShow = false
    },
    ADDCART(state, data) {
      console.log(data);
      if (state.cartData.length > 0) {
        for (var i = 0; i < state.cartData.length; i++) {
          if (state.cartData[i].product_id == data.product_id) {
            state.cartData[i].count++;
            return
          }
        }
        state.cartData.push(data)
      } else {
        state.cartData.push(data)
      }
    },
    CARTCHANGEADD(state, data) {
      for (var i = 0; i < state.cartData.length; i++) {
        if (state.cartData[i].product_id == data.product_id) {
          state.cartData[i].count++;
          return;
        }
      }
    },
    CARTCHANGEDEL(state, data) {
      for (var i = 0; i < state.cartData.length; i++) {
        if (state.cartData[i].product_id == data.product_id) {
          state.cartData[i].count--;
          return;
        }
      }
    }
  },
  // actions处理异步
  actions: {
    ADD(context) {
      context.commit("add")
    },
    DEL(context) {
      context.commit("del")
    },
    // 另一种写法
    // ADD({commit,state}){
    // commit("ADD")
    // }
    NAVSHOW(context) {
      context.commit("NAVSHOW")
    },
    HIDENAV(context) {
      context.commit("HIDENAV")
    },
    ADDCART(context, data) {
      context.commit("ADDCART", data)
    },
    CARTCHANGE(contest, obj) {
      if (obj.type == 'add') {
        contest.commit('CARTCHANGEADD', obj);
      } else {
        contest.commit('CARTCHANGEDEL', obj);
      }
    }
  },
  modules: {
  }
})

// 第二种写法
// var state = {
//   count: 100,
//   flag: false
// };
// var mutations = {
//   change(state) {
//     state.count++
//   }
// };
// var actions = {
//   ADD(context) {
//     context.commit("change")
//   }
// }
// export default new Vuex.Store({
//   state,
//   mutations,
//   actions,
// })